import { loadAmap } from '/@/utils/mapLoad';
import { ref, reactive } from 'vue';
import biaozhunIcon from '/@/assets/biaozhun.png';
import weixinIcon from '/@/assets/weixin.png';

// 导入标记点图标
import disposalMarker from '/@/assets/allocate/disposal-marker.png';
import backfillMarker from '/@/assets/allocate/backfill-marker.png';
import emissionMarker from '/@/assets/allocate/emission-marker.png';

declare namespace AMap {
	interface Map {
		add(overlay: any): void;
		remove(overlay: any): void;
		setFitView(overlays?: any[]): void;
	}
	interface Polyline {
		setMap(map: Map | null): void;
		getPath(): any[];
		show(): void;
		hide(): void;
	}
	interface Text {
		setMap(map: Map | null): void;
		show(): void;
		hide(): void;
	}
}

interface PathPoint {
	lng: number;
	lat: number;
	time?: string;
}

// 定义路径类型
type PathType = 'backfill' | 'disposal' | 'allocateStatus' | 'emission';

// 路径信息接口
interface PathInfo {
	path: AMap.Polyline;
	label?: AMap.Text;
	type: PathType;
	unitPrice?: number | string;
	allocateStatus?: number;
}

// 路由信息接口
interface RouteInfo {
	releaseType: PathType;
	status?: number;
	unitPrice?: number | string;
	rank?: number;
	rockTypeName?: string;
	distance?: number;
	path: Array<{
		lng: number;
		lat: number;
	}>;
}

// 标记点信息接口
interface MarkerInfo {
	marker: any;
	type: 'disposal' | 'backfill' | 'emission';
	path?: any;
	label?: any;
	allocateStatus?: number;
	pointName?: string;
	demandVolume?: string | number;
	budgetPrice?: string | number;
}

// 存储所有路径
const allPaths = ref<PathInfo[]>([]);

// 修改 allMarker 的定义
const allMarker = ref<MarkerInfo[]>([]);

// 默认路径样式
// const defaultPathStyle: PathStyle = {
// 	strokeColor: '#1890FF',
// 	strokeWeight: 6,
// 	strokeOpacity: 0.8,
// };

// 路径样式配置
const pathStyles = {
	allocateStatusTrue: {
		//消纳

		strokeColor: '#67C23A',
		strokeWeight: 6,
		strokeOpacity: 0.8,
	},
	allocateStatusfalse: {
		//调配
		strokeColor: '#1890FF',

		strokeWeight: 6,
		strokeOpacity: 0.8,
	},
};

// 将 buttonStates 从 const 改为 export const
export const buttonStates = reactive({
	backfill: true, //回填
	disposal: true, //消纳
	allocateStatus: false, //今日已调配
	emission: true, //
});

// 添加更新按钮状态的方法
export function updateButtonState(type: PathType, state: boolean) {
	buttonStates[type] = state;
	const mapInstance = useMap();
	mapInstance.updatePathVisibility();
	mapInstance.updateMarker();
}

// 定义 Marker 样式
const markerStyles = {
	emission: {
		//回填
		iconUrl: emissionMarker,
		iconSize: [32, 32],
		iconOffset: [-16, -32],
	},

	disposal: {
		//排放
		iconUrl: disposalMarker,
		iconSize: [32, 32],
		iconOffset: [-16, -32],
	},
	backfill: {
		//消纳
		iconUrl: backfillMarker,
		iconSize: [32, 32],
		iconOffset: [-16, -32],
	},
};

class MapManager {
	// 地图实例
	map: any = null;
	AMap: any = null;

	// 地图模式
	mapMode: string = 'normal';

	// 动画状态
	isPlaying: boolean = false;
	hasCarMarker: boolean = false;

	// 路径数据
	currentPath: PathPoint[] = [];

	// 地图元素
	pathLine: any = null;
	startMarker: any = null;
	endMarker: any = null;
	carMarker: any = null;
	animationInstance: any = null;

	// 添加一个变量来存储暂停时的位置和索引
	pausedPosition: any = null;
	pausedIndex: number = 0;
	animationOptions: any = null;

	// 围栏数据
	fences: any[] = [];

	private markers: Array<any> = [];

	constructor() {
		// 构造函数
		// 绑定方法的this指向

		this.createPathLine = this.createPathLine.bind(this);

		this.handleMapTypeSwitch = this.handleMapTypeSwitch.bind(this);
	}

	// 初始化地图
	async initMap() {
		try {
			await loadAmap();
			this.AMap = window.AMap;

			this.map = new this.AMap.Map('kupono-map', {
				zoom: 11,
				defaultType: 'normal',
				layers: [this.createDefaultLayer()],
				center: [104.06, 30.67], // 成都市中心坐标
			});

			// 添加地图控件
			this.addMapTypeControl();

			// 添加地图点击事件
			this.addMapClickEvent();

			return new Promise((resolve) => {
				this.map.on('complete', () => {
					console.log('地图初始化完成');
					resolve(true);
				});
			});
		} catch (err) {
			console.error('地图初始化失败:', err);
		}
	}

	// 创建默认图层
	createDefaultLayer() {
		return new this.AMap.createDefaultLayer({
			zooms: [3, 20],
			visible: true,
			opacity: 1,
			zIndex: 0,
			customStyle: {
				building: {
					visible: true,
					fillColor: '#FFFFFF',
					strokeColor: '#FFFFFF',
				},
				road: {
					visible: false,
				},
				text: {
					visible: false,
				},
			},
		});
	}
	// 设置中心点
	setCenter(position: [number, number]) {
		this.map.setCenter(position);
	}
	// 添加地图类型切换控件
	addMapTypeControl() {
		const mapTypeContainer = document.createElement('div');
		mapTypeContainer.className = 'map-type-switch';
		mapTypeContainer.id = 'mapTypeSwitch';
		mapTypeContainer.style.display = 'block';
		mapTypeContainer.innerHTML = this.createMapTypeSwitchHTML();

		// 添加切换事件
		mapTypeContainer.addEventListener('click', (e) =>
			this.handleMapTypeSwitch(e),
		);

		this.map.getContainer().appendChild(mapTypeContainer);
	}

	// 创建地图类型切换HTML
	createMapTypeSwitchHTML() {
		return `
      <div class="map-type-options">
        <div class="map-type-option ${this.mapMode === 'normal' ? 'active' : ''}"
          data-type="标准地图">
          <img src="${biaozhunIcon}" alt="标准地图" class="map-icon" />
        </div>
        <div class="map-type-option ${this.mapMode === 'satellite' ? 'active' : ''}"
          data-type="卫星地图">
          <img src="${weixinIcon}" alt="卫星地图" class="map-icon" />
        </div>
      </div>
    `;
	}

	// 处理地图类型切换
	handleMapTypeSwitch(e: MouseEvent) {
		const target = (e.target as HTMLElement).closest('.map-type-option');
		if (!target) return;

		const type = target.getAttribute('data-type');
		this.mapMode = type === '标准地图' ? 'normal' : 'satellite';

		// 更新按钮状态
		this.updateMapTypeSwitchStatus(type);

		// 切换地图图层
		this.switchMapLayers();
	}

	// 更新地图类型切换按钮状态
	updateMapTypeSwitchStatus(selectedType: string | null) {
		const container = document.getElementById('mapTypeSwitch');
		if (!container) return;

		container.querySelectorAll('.map-type-option').forEach((el) => {
			el.classList.toggle(
				'active',
				el.getAttribute('data-type') === selectedType,
			);
		});
	}

	// 切换地图图层
	switchMapLayers() {
		if (this.mapMode === 'satellite') {
			const satelliteLayer = new this.AMap.TileLayer.Satellite();
			const roadNetLayer = new this.AMap.TileLayer.RoadNet();
			this.map.setLayers([satelliteLayer, roadNetLayer]);
		} else {
			// 移除现有图层
			const layers = this.map.getLayers();
			layers.forEach((layer: any) => {
				if (layer.CLASS_NAME != 'AMap.VectorLayer') {
					this.map.remove(layer);
				}
			});

			// 恢复标准地图
			this.map.setLayers([this.createDefaultLayer()]);
		}
	}

	// 添加地图点击事件
	addMapClickEvent() {
		this.map.on('click', (e: any) => {
			console.log('Clicked on map:', e.lnglat);
			// 这里可以添加其他点击事件处理逻辑
		});
	}

	// 创建路径线
	createPathLine(path: PathPoint[], info: any) {
		console.log(buttonStates);

		if (!path || !path.length) return;

		// 确保 releaseType 是有效的类型
		const releaseType = info.releaseType == 2 ? 'backfill' : 'disposal';
		console.log('releaseType', releaseType);
		const pathStyle =
			info.allocateStatus == 0
				? pathStyles['allocateStatusfalse']
				: pathStyles['allocateStatusTrue'];

		// 创建折线
		const polyline = new this.AMap.Polyline({
			path: path.map((p) => [p.lng, p.lat]),
			...pathStyle,
			zIndex: 100,
		});

		// 计算路径中点
		const midIndex = Math.floor(path.length / 2);
		const midPoint = [path[midIndex].lng, path[midIndex].lat];

		// 创建价格标签
		const priceLabel = new this.AMap.Text({
			text: `TOP ${info.rank || ''}\n排放类型：${info.rockTypeName || ''}\n距离：${info.distance || ''}km | 单价：${info.unitPrice || ''}元/方・公里`,
			position: midPoint,
			offset: new this.AMap.Pixel(0, -40),
			style: {
				background: pathStyle.strokeColor,
				color: '#fff',
				border: 'none',
				fontSize: '12px',
				fontWeight: 'bold',
				padding: '6px 10px',
				'text-align': 'left',
				'border-radius': '4px',
				'box-shadow': '0 2px 6px rgba(0,0,0,0.1)',
				'line-height': '1.5',
				'white-space': 'pre',
				'word-break': 'normal',
				'max-width': '250px',
				overflow: 'hidden',
				zIndex: 100,
			},
		});

		// 添加点击事件：高亮当前标签并置顶
		priceLabel.on('click', () => {
			// 取消所有标签高亮
			allPaths.value.forEach((p) => {
				if (p.label) {
					p.label.setStyle({
						background:
							p.type === 'backfill' || p.type === 'disposal'
								? pathStyles[
										p.allocateStatus == 0
											? 'allocateStatusfalse'
											: 'allocateStatusTrue'
									].strokeColor
								: '#1890FF',
						color: '#fff',
						border: 'none',
						fontWeight: 'bold',
						zIndex: 100,
					});
					if (typeof p.label.setzIndex === 'function') {
						p.label.setzIndex(100);
					}
				}
			});
			// 高亮当前
			priceLabel.setStyle({
				background: '#E6F7FF', // 柔和蓝色
				color: '#1890FF', // 主题蓝
				border: '1.5px solid #1890FF',
				fontWeight: 'bold',
				boxShadow: '0 0 8px 2px rgba(24,144,255,0.15)',
				borderRadius: '6px',
				zIndex: 999,
			});
			if (typeof priceLabel.setzIndex === 'function') {
				priceLabel.setzIndex(999);
			}
		});

		// 将轨迹添加到地图
		polyline.setMap(this.map);
		priceLabel.setMap(this.map);

		// 存储轨迹信息
		const pathInfo: PathInfo = {
			path: polyline,
			label: priceLabel,
			type: releaseType,
			unitPrice: info.unitPrice,
			allocateStatus: info.allocateStatus,
		};

		polyline.setOptions(pathInfo);

		allPaths.value.push(pathInfo);

		// 根据当前按钮状态决定是否显示
		this.updatePathVisibility();
	}
	//更新图标显示状态
	updateMarker() {
		allMarker.value.forEach((marker) => {
			let shouldShow = false;

			console.log(buttonStates, marker.type);
			// 检查回填/消纳状态
			if (marker.type === 'backfill' && buttonStates.backfill) {
				shouldShow = true;
			}
			if (marker.type === 'disposal' && buttonStates.disposal) {
				shouldShow = true;
			}
			if (marker.type === 'emission' && buttonStates.emission) {
				shouldShow = true;
			}
			console.log(shouldShow, 44444);

			// 检查调配状态

			if (shouldShow) {
				marker.marker.show();
			} else {
				marker.marker.hide();
			}
		});
	}

	// 更新轨迹显示状态
	updatePathVisibility() {
		allPaths.value.forEach((path) => {
			let shouldShow = false;

			console.log(buttonStates, path.type);
			// 检查回填/消纳状态
			if (path.type === 'backfill' && buttonStates.backfill) {
				if (path.allocateStatus == 1 && buttonStates.allocateStatus) {
					shouldShow = true;
				}

				if (!buttonStates.allocateStatus) {
					shouldShow = true;
				}
			}
			if (path.type === 'disposal' && buttonStates.disposal) {
				if (path.allocateStatus == 1 && buttonStates.allocateStatus) {
					shouldShow = true;
				}

				if (!buttonStates.allocateStatus) {
					shouldShow = true;
				}
			}
			console.log(shouldShow, 44444);

			// 检查调配状态

			if (shouldShow) {
				path.path.show();
				path.label?.show();
			} else {
				path.path.hide();
				path.label?.hide();
			}
		});
	}

	// 清除所有轨迹相关的元素
	clearTrackElements() {
		if (this.pathLine) this.map.remove(this.pathLine);
		if (this.startMarker) this.map.remove(this.startMarker);
		if (this.endMarker) this.map.remove(this.endMarker);
		if (this.carMarker) {
			if (this.carMarker.stopMove) {
				this.carMarker.stopMove();
			}
			this.map.remove(this.carMarker);
		}
	}

	// 销毁地图
	destroyMap() {
		if (this.map) {
			this.map.destroy();
			this.map = null;
			this.AMap = null;
		}
	}

	// 添加标记点
	addMarker(
		position: { lng: number; lat: number },
		type: 'disposal' | 'backfill' | 'emission',
		info: any,
	) {
		if (!position.lng || !position.lat) return;

		const style = markerStyles[type];

		console.log('style', style, type);
		const icon = new this.AMap.Icon({
			size: new this.AMap.Size(style.iconSize[0], style.iconSize[1]),
			image: style.iconUrl,
			imageSize: new this.AMap.Size(style.iconSize[0], style.iconSize[1]),
		});

		const marker = new this.AMap.Marker({
			position: [position.lng, position.lat],
			icon: icon,
			offset: new this.AMap.Pixel(style.iconOffset[0], style.iconOffset[1]),
			extData: info,
		});

		// 获取类型对应的颜色

		// 获取类型名称
		const getTypeName = (type: any) => {
			if (type == 'backfill') return '回填';
			if (type == 'emission') return '排放';
			return '消纳';
		};

		// 优化信息窗体内容
		const content = `
			<div class="marker-info-window" style="
				padding: 15px; 
				border-radius: 8px; 
				min-width: 220px;
				background: #fff;
				position: relative;
			">
				<div style="
					font-size: 16px; 
					font-weight: bold; 
					border-bottom: 1px solid #eee;
					padding-bottom: 10px;
					margin-bottom: 10px;
					color: #333;
					max-width: 300px;
				">${type == 'emission' ? info.emissionPointName : info.receivePointName || '点位信息'}</div>
				
				<div style="margin-bottom: 8px; color: #666;">
					物料类型: <span style="color: #1890FF; font-weight: bold;">${info.rockTypeName || '--'}</span>
				</div>

				<div style="display: flex; margin-bottom: 8px;">
					<div style="width: 100px; color: #666;">今日${getTypeName(type)}方量:</div>
					<div style="color: #1890FF; font-weight: bold;">${type == 'emission' ? info.emissionVolume : info.receiveVolume || '--'}方</div>
				</div>

				<div style="display: flex; margin-bottom: 8px;">
					<div style="width: 100px; color: #666;">今日${getTypeName(type)}预算:</div>
					<div style="color: #1890FF; font-weight: bold;">${type == 'emission' ? info.emissionBudget : info.receiveBudget || '--'}元/${type == 'emission' ? '车' : '方'}</div>
				</div>
			</div>
		`;

		// 创建信息窗体
		const infoWindow = new this.AMap.InfoWindow({
			content: content,
			offset: new this.AMap.Pixel(0, -30),
			closeWhenClickMap: false,
		});

		marker.on('click', () => {
			infoWindow.open(this.map, marker.getPosition());
		});

		const markerInfo = {
			marker: marker,
			...info,
			type: type,
		};
		allMarker.value.push(markerInfo);

		marker.setMap(this.map);
		this.markers.push(marker);
		this.updateMarker();
	}

	// 清除所有标记点
	clearMarkers() {
		this.markers.forEach((marker) => {
			marker.setMap(null);
		});
		this.markers = [];
	}

	// 修改 clearAllPaths 方法，只清除路径，不清除标记点
	clearAllPaths() {
		// 只清除路径和标签
		allPaths.value.forEach((path) => {
			path.path.setMap(null);
			path.label?.setMap(null);
		});
		allPaths.value = [];
	}

	// 新增方法，清除所有路径和标记点
	clearAll() {
		// 清除路径
		this.clearAllPaths();

		// 清除标记点
		this.clearMarkers();
	}

	// 设置地图视野以包含所有轨迹
	setFitView() {
		this.map.setFitView();
	}

	// 创建路径
	createPath(info: RouteInfo) {
		try {
			const polyline = new this.AMap.Polyline({
				path: info.path.map((p) => [p.lng, p.lat]),
				...pathStyles[info.releaseType as PathType],
				zIndex: 100,
			});

			// 创建价格标签
			const priceLabel = new this.AMap.Text({
				text: `${info.unitPrice}元/km`,
				position: this.calculateMidpoint(info.path),
				offset: new this.AMap.Pixel(0, -40),
				style: {
					background: pathStyles[info.releaseType as PathType].strokeColor,
					color: '#fff',
					border: 'none',
					padding: '4px 10px',
					'border-radius': '4px',
				},
			});

			// 将轨迹添加到地图
			polyline.setMap(this.map);
			priceLabel.setMap(this.map);

			// 存储轨迹信息
			const pathInfo: PathInfo = {
				path: polyline,
				label: priceLabel,
				type: info.releaseType,
				unitPrice: info.unitPrice,
				allocateStatus: info.status,
			};

			polyline.setOptions(pathInfo);

			allPaths.value.push(pathInfo);

			// 根据当前按钮状态决定是否显示
			this.updatePathVisibility();
		} catch (error) {
			console.error('创建路径失败:', error);
		}
	}

	// 计算路径中点
	calculateMidpoint(path: Array<{ lng: number; lat: number }>) {
		if (!path || path.length === 0) {
			return [0, 0];
		}

		const midIndex = Math.floor(path.length / 2);
		return [path[midIndex].lng, path[midIndex].lat];
	}

	// 显示指定类型的路径
	showPathsByType(type: PathType) {
		allPaths.value.forEach((path) => {
			if (
				path.type === type ||
				(type === 'allocateStatus' && path.allocateStatus == 1)
			) {
				path.path.show();
				path.label?.show();
			}
		});
	}

	// 隐藏指定类型的路径
	hidePathsByType(type: PathType) {
		allPaths.value.forEach((path) => {
			if (
				path.type === type ||
				(type === 'allocateStatus' && path.allocateStatus == 1)
			) {
				path.path.hide();
				path.label?.hide();
			}
		});
	}

	// 显示指定类型的标记点
	showMarkerByType(type: PathType) {
		allMarker.value.forEach((markerInfo) => {
			if (
				markerInfo.type === type ||
				(type === 'allocateStatus' && markerInfo.allocateStatus === 1)
			) {
				markerInfo.marker.show();
			}
		});
	}

	// 隐藏指定类型的标记点
	hideMarkerByType(type: PathType) {
		allMarker.value.forEach((markerInfo) => {
			if (
				markerInfo.type === type ||
				(type === 'allocateStatus' && markerInfo.allocateStatus === 1)
			) {
				markerInfo.marker.hide();
			}
		});
	}
}

// 创建单例
let mapInstance: MapManager | null = null;

export function useMap() {
	if (!mapInstance) {
		mapInstance = new MapManager();
	}
	return mapInstance;
}
